package handler

import (
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/spf13/cast"
	"honghu_be/common"
	"honghu_be/dal"
	"honghu_be/model"
	"honghu_be/model/vo"
)

func UpdateAd(c *gin.Context) {
	req := &model.UpdateAdRequest{}
	if err := c.ShouldBindBodyWith(req, binding.JSON); err != nil {
		c.JSON(400, err.Error())
		return
	}
	resp, err := updateAd(c, req)
	if err != nil {
		common.WriteError(c, err)
		return
	}
	c.JSON(200, resp)
}

func updateAd(c *gin.Context, req *model.UpdateAdRequest) (*model.UpdateAdResponse, error) {
	po := req.Ad.ToPo()
	err := dal.UpdateAd(c, cast.ToInt(req.Ad.AdId), po)
	if err != nil {
		return nil, err
	}
	return &model.UpdateAdResponse{
		Meta: common.MetaOk,
		Ad:   vo.ToAdVo(po),
	}, nil
}
